package com.broada.apm.ajax;

import java.io.Serializable;
import java.util.HashMap;

import org.apache.commons.lang.StringUtils;

import com.broada.apm.model.PagingList;

public class Result extends HashMap<String, Object> implements Serializable {
	/**
	 * <code>serialVersionUID</code>
	 */
	private static final long serialVersionUID = 1L;

	public Result() {
		addData("meta", new HashMap<String, Object>());
		addData("status", "success");
	}
	public static Result ok() {
	    return new Result();
	}
	public static Result invalid() {
	    Result result = new Result();
        result.addData("status", "invalid");
        return result;
	}
	public static Result err(String message) {
        Result result = new Result();
        result.setFailMessage(message);;
        return result;
    }
	public boolean isOk(){
	    return StringUtils.equals(get("status").toString().trim(), "success");
	}
	public boolean isInvalid() {
	    return StringUtils.equals(get("status").toString().trim(), "invalid");
	}
	public boolean isErr(){
	    return StringUtils.equals(get("status").toString().trim(), "fail");
	}
	public Result addData(String name, Object obj) {
		put(name, obj);
		return this;
	}

	public <T> void addPagingList(PagingList<T> obj) {
		HashMap<String, Object> meta = getMeta();
		meta.put("pageSize", obj.getPageSize());
		meta.put("pageIndex", obj.getStartPage());
		meta.put("total", obj.getTotalRecords());
		meta.put("totalPage", obj.getTotalPages());
		this.put("result", obj.getData());
	}
	
	public void setPageSize(int pagesize) {
		HashMap<String, Object> meta = getMeta();
		meta.put("pageSize", pagesize);
	}

	public void setPageIndex(int pageindex) {
		HashMap<String, Object> meta = getMeta();
		meta.put("pageIndex", pageindex);
	}

	public void setTotal(int total) {
		HashMap<String, Object> meta = getMeta();
		meta.put("total", total);
	}

	public void setTotalPage(int totalPage) {
		HashMap<String, Object> meta = getMeta();
		meta.put("totalPage", totalPage);
	}

	public void setOrderBy(String field, boolean desc) {
		HashMap<String, Object> meta = getMeta();
		meta.put("orderBy", field);
		if (desc) {
			meta.put("desc", desc);
		} else {
			meta.remove("desc");
		}
	}
	
	protected HashMap<String, Object> getMeta() {
		return (HashMap<String, Object>) get("meta");
	}

	public void setFailMessage(String message) {
		this.addData("status", "fail");
		this.addData("message", message);
	}
	
	public void setInvalidMessage(String message) {
	    this.addData("status", "invalid");
	    this.addData("message", message);
	}
	
}
